package com.my.bytes;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @description:
 * @author: marshal
 * @date: 2021-08-24 10:24 AM
 * All byte stream classes are descended from InputStream and OutputStream.
 * <p>
 * reference: https://docs.oracle.com/javase/tutorial/essential/io/bytestreams.html
 */
public class CopyBytes {
    public static void main(String[] args) {
        FileInputStream in = null;
        FileOutputStream out = null;
        try {
            in = new FileInputStream("file/xanadu.txt");
            out = new FileOutputStream("file/outagain.txt");

            int c;
            while ((c = in.read()) != -1) {
                //  writes the output stream, one byte at a time
                out.write(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // Closing a stream when it's no longer needed is very important — so important that CopyBytes uses a finally block to guarantee
            // that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
